package agriculture.mq;

import agriculture.dto.StockDTO;
import agriculture.service.OrderService;
import agriculture.system.api.model.OrderPaidMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 监听支付成功的 MQ 消息
 */
@Slf4j
@Component
public class OrderMQListener {
    @Resource
    private OrderService orderService;

    /**
     * 监听订单支付成功消息
     */
//    @RabbitListener(queues = "order.paid.queue")
//    public void onOrderPaid(OrderPaidMessage message) {
//        log.info("【MQ监听】收到订单支付成功消息: {}", message);
//
//        // 更新订单状态
//        orderService.updateOrderStatus(message.getOrderNumber(), "1",message.getPayTime());
//
//        // 插入订单详情记录
//        orderService.insertOrderDetails(message.getOrderNumber(),message.getQuantity(),message.getPaymentMethod());
//
//        //根据订单号去查询对应的商品ID
//        Long productId = orderService.getProductIdByOrderNumber(message.getOrderNumber());
//        //远程调用商品服务扣减库存
//        StockDTO stockDTO = new StockDTO();
//        stockDTO.setProductId(productId);
//        stockDTO.setQuantity(message.getQuantity());
//
//    }
    @RabbitListener(queues = "order.paid.queue")
    public void onOrderPaid(OrderPaidMessage message) {
        log.info("【MQ监听】收到订单支付成功消息: {}", message);
        try {
            // ✅ 把处理逻辑交给服务层事务方法
            orderService.handleOrderPaid(message);
        } catch (Exception e) {
            log.error("【MQ监听】订单支付处理失败，消息将可能重试或进死信队列: {}", message, e);
            throw e; // 抛出异常，RabbitMQ会进行重试或进入死信队列
        }
    }
}
